<!--需求列表 DemandSys-->
<template>
  <div class='page_format'>
    <!-- 顶部统计部分 -->
    <el-row :gutter="20" class="statistics-row">
      <el-col :span="4" v-for="(item, index) in statisticsData" :key="index">
        <div class="stat-box">
          <p>{{ item.label }}</p>
          <h3>{{ item.value }}</h3>
        </div>
      </el-col>
    </el-row>
    <div class="my_Select">
      <el-form :inline="true" class="search-form">
        <el-form-item>
          <el-button v-if="handleJumpButton" class="bt-color-tjd" type="primary" style="margin-right: 10px;"
                     @click="retPath">返回
          </el-button>
          <el-select style="width: 110px;" v-model="status" placeholder="全部" size="small" clearable
                     @change="handleQuery">
            <el-option
              v-for="(item, index) in statusData"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="kind" placeholder="品类" clearable style="width:120px;margin-right:6px" size="small"
                     @change="handleQuery">
            <el-option
              v-for="item in deviceKindData"
              :key="item.id"
              :label="`${item.label}`"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input style="width:180px;margin-right:6px" size="small" placeholder="需求名称/项目ID" v-model="queryValue"
                    clearable></el-input>
          <el-button size="small" @click="handleQuery" icon="el-icon-search" type="primary">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table :data="list" border style="width: 100%">
      <el-table-column type="index" :index="sort" label="序号" width="50"></el-table-column>
      <el-table-column prop="demandId" label="ID"></el-table-column>
      <el-table-column prop="demandName" label="需求名称"/>
      <el-table-column prop="devId" label="项目ID" :formatter="formatDevId"/>
      <el-table-column prop="priority" label="优先级" width="80"/>
      <el-table-column label="数量/大小" align="center">
        <template v-slot="scope">
          <div><span>{{ scope.row.dailIdCount }}</span></div>
          <div><span>（{{ scope.row.dialSizeTotal }}kb，{{ scope.row.resSizeTotal }}kb）</span></div>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template v-slot="scope">
          <span>{{ getStatusText(scope.row.status) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否带缩略图">
        <template v-slot="scope">
          <span>{{ scope.row.thumbnailStatus === '0' ? '否' : '是' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="设备信息" align="left">
        <template v-slot="scope">
          <div><span>分辨率：{{ scope.row.devScrDpi }}</span></div>
          <div><span>主控平台：{{ getMasterControlPlatformText(scope.row.devIcMseries) }}</span></div>
          <div><span>主控型号：{{ scope.row.devIcMcode }}</span></div>
          <div><span>屏幕形状：{{ getShapeText(scope.row.devScrShape)}}</span></div>
        </template>
      </el-table-column>
      <el-table-column label="品类" width="80">
        <template v-slot="scope">
          <span>{{ getDeviceKindText(scope.row.kind) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="projectManager" label="项目经理">
        <template v-slot="scope">
          <div v-if="is_show_button('demand_query')"
               @click="handleJumpProjectManager(scope.row)"
               style="color: #409eff; cursor: pointer;">
            {{ getUserNameText(scope.row.projectManager) }}
          </div>
          <span v-else>{{ getUserNameText(scope.row.projectManager) }}</span>
        </template>
      </el-table-column>

<!--      <el-table-column prop="masterDeveloper" label="主程开发人">-->
<!--        <template v-slot="scope">-->
<!--          <div v-if="is_show_button('demand_query')"-->
<!--               @click="handleJumpMasterDeveloper(scope.row)"-->
<!--               style="color: #409eff; cursor: pointer;">-->
<!--            {{ getUserNameText(scope.row.masterDeveloper) }}-->
<!--          </div>-->
<!--          <span v-else>{{ getUserNameText(scope.row.masterDeveloper) }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column prop="createTime" label="创建时间"/>
      <el-table-column prop="finishTime" label="预计完成时间"/>
      <el-table-column fixed="right" label="操作" width="80">
        <template v-slot="scope">
          <el-button
            v-for="(button, index) in getActionButtons(scope.row)"
            v-show ="button.show"
            :key="index"
            @click="button.handler(scope.row)"
            type="text"
            size="small"
          >
            {{ button.label }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <el-dialog :visible.sync="changeStatus1Show" title="启动需求" center append-to-body @close="closeStatusDialog">
      <el-form :model="changeStatusForm">
<!--        <el-form-item label="主程开发人：" :label-width="formLabelWidth" style="display: inline-block; width: 100%;">-->
<!--          <el-cascader v-model="changeStatusForm.masterDeveloper"-->
<!--                       placeholder="请选择接收人员" multiple-->
<!--                       :options="userCascadeData"-->
<!--                       :props="{ multiple: false, emitPath: false }"-->
<!--                       :show-all-levels="false"-->
<!--                       filterable></el-cascader>-->
<!--        </el-form-item>-->
        <el-form-item label="项目ID：" :label-width="formLabelWidth" style="display: inline-block; width: 42%;">
          <el-input v-model="changeStatusForm.devId" placeholder="请输入项目ID" autocomplete="off" @blur="validateDevId"></el-input>
        </el-form-item>
        <el-form-item label="启动时间：" :label-width="formLabelWidth">
          <template>
            <el-date-picker v-model="changeStatusForm.startUpTime" type="datetime"
                            format="yyyy-MM-dd HH:mm:ss"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            :picker-options="startPickerOptions(changeStatusForm.finishTime)"
            ></el-date-picker>
          </template>
          预计完成时间
          <template>
            <el-date-picker v-model="changeStatusForm.finishTime" type="datetime"
                            format="yyyy-MM-dd HH:mm:ss"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            :picker-options="endPickerOptions(changeStatusForm.startUpTime)"></el-date-picker>
          </template>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeStatusDialog">取 消</el-button>
        <el-button class="bt-color-tjd" type="primary"
                   :loading="submitLoading" @click="saveStatusDataApi">确 定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="定制需求" :visible.sync="dialogFormVisible" center width="500px" @close="closeDialog">
      <el-form :model="form" :rules="rules" ref="dialogForm">
        <el-form-item label="预留空间（kb）：" :label-width="formLabelWidth" style="display: inline-block; width: 100%;"
                      prop="reserveSpace">
          <el-input v-model="form.reserveSpace" placeholder="请输入预留空间（kb）" autocomplete="off"
                    type="number"></el-input>
        </el-form-item>
        <el-form-item label="预留个数：" :label-width="formLabelWidth" style="display: inline-block; width: 100%;"
                      prop="reserveCount">
          <el-input v-model="form.reserveCount" autocomplete="off" placeholder="请输入预留个数"
                    type="number"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog" :disabled="submitLoading">取 消</el-button>
        <el-button class="bt-color-tjd" type="primary"
                   @click="saveDataApi" :loading="submitLoading">确 定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="查看需求详情" :visible.sync="detailShow" center width="1200px"
               @close="detailDialog">
      <div>
        <el-divider :style="{ 'font-size': '16px', 'margin-top': '20px', 'margin-bottom': '20px' }"
                    content-position="left" >基础配置</el-divider>
        <el-form :model="form" :label-width="formLabelWidth" size="mini" class="detail">
          <el-form-item label="需求名称：" :label-width="formLabelWidth" style="display: inline-block; width: 30%;">
            {{ form.demandName }}
          </el-form-item>
          <el-form-item label="优先级：" :label-width="formLabelWidth" style="display: inline-block; width: 30%;">
            {{ getPriorityText(form.priority) }}
          </el-form-item>
          <el-form-item label="主控信息：" :label-width="formLabelWidth" style="display: inline-block; width: 40%;">
            <span>{{ form.devIcMseries }},{{ form.devIcMcode }}</span>
          </el-form-item>
          <el-form-item label="屏幕形状：" :label-width="formLabelWidth" style="display: inline-block; width: 30%;">
            <span>{{ getShapeText(form.devScrShape) }}</span>
          </el-form-item>
          <el-form-item label="分辨率：" :label-width="formLabelWidth" style="display: inline-block; width: 30%;">
            <span>{{ form.devScrDpi }}</span>
          </el-form-item>
          <el-form-item label="是否带缩略图：" :label-width="formLabelWidth" style="display: inline-block; width: 40%;">
            <span>{{ form.thumbnailStatus === '0' ? '否' : '是' }}</span>
          </el-form-item>
          <el-form-item label="项目类型：" :label-width="formLabelWidth" style="display: inline-block; width: 30%;">
            <span>{{ getTypeText(form.type) }}</span>
          </el-form-item>
          <el-form-item label="项目经理：" :label-width="formLabelWidth" style="display: inline-block; width: 30%;">
            <span>{{ getUserNameText(form.projectManager) }}</span>
          </el-form-item>
<!--          <el-form-item label="主程开发：" :label-width="formLabelWidth" style="display: inline-block; width: 40%;">-->
<!--            <span>{{ form.masterDeveloper }}</span>-->
<!--          </el-form-item>-->
          <el-form-item label="备注：" :label-width="formLabelWidth" style="display: inline-block; width: 100%;">
            <span>{{ form.remark }}</span>
          </el-form-item>
        </el-form>
      </div>
      <el-divider :style="{ 'font-size': '16px', 'margin-top': '20px', 'margin-bottom': '20px' }"
                  content-position="left" >设计资源配置</el-divider>
      <el-table :data="form.crmDemandViewList" border style="width: 100%">
        <el-table-column type="index" fixed :index="sort" label="序号" width="60" align="center"></el-table-column>
        <el-table-column prop="dialNameZh" label="表盘名称" align="center"></el-table-column>
        <el-table-column label="预览图" width="144" align="center">
          <template v-slot="scope">
            <img style="width: 120px;" :src="scope.row.newPreviewUrl" alt="预览图">
          </template>
        </el-table-column>
        <el-table-column label="表盘大小（含缩略图）" align="center" >
          <template v-slot="scope">
            {{scope.row.dialSize}}kb
          </template>
        </el-table-column>
        <el-table-column label="表盘大小（不含缩略图）" align="center" >
          <template v-slot="scope">
            {{ scope.row.resSize }}kb
          </template>
        </el-table-column>
        <el-table-column label="表盘类型" align="center" >
          <template v-slot="scope">
            <span>{{ getDialTypeText(scope.row.dialTypeId) }}</span>
          </template>
        </el-table-column>
      </el-table>

      <div style="margin-top: 20px; text-align: left;">
        所占空间：
        含缩略图-{{ form.dialSizeTotal }} KB，
        不含缩略图-{{ form.resSizeTotal }} KB
      </div>
      <div style="margin-top: 20px; text-align: left;">
        <!-- 文件名显示并添加下载链接 -->
        附件：
        <a v-if="form.annexUrl" :href="form.annexUrl" download :title="form.annexName">
          {{ form.annexName }}
        </a>
      </div>
      <div style="margin-top: 20px; text-align: left;">
        <el-link type="primary" @click="handleDemandLogClick(form)" >查看操作记录</el-link>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialog" :disabled="submitLoading">取 消</el-button>
      </div>
    </el-dialog>

    <Toast :dialogVisible="dialogVisible" @isDelete="deleteDataApi"></Toast>
    <DemandLog :id="`${routerDialId}`" @isDev="demandLogDialogShow = false"
                           :demandLogDialogShow="demandLogDialogShow"></DemandLog>

  </div>
</template>

<script>
import { post } from '@/api/my_axios'
import { changSort } from '@/utils/aqi'

export default {
  name: '',
  data () {
    return {
      handleJumpButton: false, // 跳转返回按钮
      demandLogDialogShow: false, // 日志弹窗
      detailShow: false, // 详情
      changeStatus1Show: false, // 按钮loading
      submitLoading: false, // 按钮loading
      dialogFormVisible: false,
      dialogVisible: false,
      dialogShowS: false,
      form: {
        demandId: '',
        demandName: '',
        kind: '',
        priority: '',
        status: '',
        thumbnailStatus: '',
        devIcMseries: '',
        devIcMcode: '',
        devScrShape: '',
        devScrDpi: '',
        devIcFlash: '',
        projectManager: '',
        masterDeveloper: '',
        startUpTime: '',
        finishTime: '',
        remark: '',
        devId: '',
        reserveCount: '',
        reserveSpace: '',
        thumbnailSizeTotal: 0,
        resSizeTotal: 0,
        dialSizeTotal: 0,
        dailIdCount: 0,
        crmDemandViewList: [],
        annexName: '',
        annexUrl: '',
        annexSize: ''
      },
      changeStatusForm: {
        demandId: '',
        demandName: '',
        kind: '',
        priority: '',
        status: '',
        thumbnailStatus: '',
        devIcMseries: '',
        devIcMcode: '',
        devScrShape: '',
        devScrDpi: '',
        devIcFlash: '',
        projectManager: '',
        masterDeveloper: '',
        startUpTime: '',
        finishTime: '',
        remark: '',
        devId: '',
        reserveCount: '',
        reserveSpace: ''
      },
      list: [],
      statisticsData: [],
      devIcMseriesData: [],
      devScrDpiData: [],
      devIcMcodeData: [],
      devScrShapeData: [], // 屏幕形状
      devIcFlashData: [], // flash存储空间
      deviceKindData: [], // 项目品类
      userCascadeData: [], // 角色用户关联
      userCascadeList: [],
      priorityData: [], // 优先级
      projectManager: this.$store.state.module1.UserInfo.roleId === 4 ? this.$store.state.module1.UserInfo.userName
        : '',
      masterDeveloper: '',
      formLabelWidth: '140px',
      pageSize: 20,
      pageNum: 1,
      total: 0,
      id: '',
      queryValue: '',
      devIcMseries: '',
      devIcMcode: '',
      devScrShape: '',
      devScrDpi: '',
      queryId: '',
      kind: '',
      status: '',
      routerDialId: '',
      rules: {
        reserveSpace: [{ required: true, message: '必填项不能为空！', trigger: 'change' }],
        reserveCount: [{ required: true, message: '必填项不能为空！', trigger: 'change' }]
      },
      statusData: [
        { value: '0', label: '待启动' },
        { value: '1', label: '进行中' },
        { value: '2', label: '已延期' },
        { value: '3', label: '已完成' },
        { value: '4', label: '已取消' }
      ],
      typeData: [
        { value: 'domestic', label: '国内版（公版）' },
        { value: 'overseas', label: '海外版' }
      ],
      dialTypeData: [
        { value: '112', label: '数字' },
        { value: '113', label: '模拟' }
      ]
    }
  },

  computed: {
    currentUserId () {
      // 假设用户 ID 存在 Vuex 里
      return this.$store.state.module1.UserInfo.userName
    }
  },

  watch: {
    'form.devIcMseries' (val) {
      if (val) {
        this.getSysDictList(val)
      }
    }
  },

  mounted () {
    this.getDictSortData()
    this.getDemandStatistics()
    this.getDemandList()
    this.getRoleCascadeRelation()
  },

  methods: {
    // 排序 （序号）
    sort (index) {
      return changSort(index, this.pageNum, this.pageSize)
    },

    // 时间选择要大于当前的系统时间
    startPickerOptions (value) {
      return {
        disabledDate (time) {
          if (value) {
            // 禁用如果结束时间不为空，则小于结束时间,大于当前时间
            return (time.getTime() < Date.now() - 8.64e7 || new Date(value).getTime() - 8.64e7 < time.getTime())
          } else {
            // 开始时间不选时，结束时间最大值小于等于当天
            return time.getTime() < Date.now() - 8.64e7
          }
        }
      }
    },

    // 结束时间不能小于开始时间
    endPickerOptions (value) {
      return {
        disabledDate (time) {
          if (value) {
            // 禁用如果开始时间不为空，则结束时间大于开始时间一天
            return new Date(value).getTime() > time.getTime() - 8.64e7
          } else {
            // 开始时间不选时，结束时间最大值小于等于当天
            return time.getTime() < Date.now() - 8.64e7
          }
        }
      }
    },

    formatDevId (row) {
      return row.devId ? row.devId : '未启动'
    },

    // 按钮权限判断
    canOperate (row) {
      return (
        this.is_show_button('competence_demand_save_all') ||
        (this.is_show_button('competence_demand_save_only') && row.projectManager === this.currentUserId)
      )
    },
    getActionButtons (row) {
      const canOperate = this.canOperate(row)
      const isStatus01or2 = row.status === '1' || row.status === '2'

      return [
        {
        },
        {
          label: '查看',
          show: true,
          handler: this.handleDetail
        },
        {
          label: '启动',
          show: row.status === '0' && this.is_show_button('button_demand_status') && canOperate,
          handler: this.changeStatus1
        },
        {
          label: '定制',
          show: row.status === '0' && this.is_show_button('button_demand_status') && row.devScrShape !== '9' && canOperate,
          handler: this.handleClick
        },
        {
          label: '取消',
          show: row.status === '0' && this.is_show_button('button_demand_cancel') && canOperate,
          handler: this.changeStatus4
        },
        {
          label: '完成',
          show: isStatus01or2 && this.is_show_button('button_demand_status') && canOperate,
          handler: this.changeStatus3
        },
        {
          label: '协调',
          show: isStatus01or2 && this.is_show_button('button_demand_status') && canOperate,
          handler: this.changeStatus0
        }
      ]
    },

    // 项目经理的转化
    getUserNameText (value) {
      // 遍历 userCascadeData，查找匹配的 userName，并返回对应的 nickName
      for (const manager of this.userCascadeData) {
        const user = manager.children.find(child => child.value === value)
        if (user) {
          return user.label // 返回对应的 nickName
        }
      }
      return '' // 如果未找到，返回空字符串
    },

    // 主控平台转化
    getMasterControlPlatformText (value) {
      if (value) {
        const devFuncArr = value.split(',')
        const newDevFunc = []
        devFuncArr.forEach(item => {
          this.devIcMseriesData.forEach(ele => {
            if (ele.value === item) newDevFunc.push(ele.label)
          })
        })
        return newDevFunc.join(',')
      }
      return ''
    },

    // 项目类型转化
    getTypeText (value) {
      const dto = this.typeData.find(v => v.value === value)
      return dto ? dto.label : ''
    },

    // 优先级转化
    getPriorityText (value) {
      const dto = this.priorityData.find(v => v.value === value)
      return dto ? dto.label : ''
    },

    // 表盘类型转化
    getDialTypeText (value) {
      const dto = this.dialTypeData.find(v => v.value === value)
      return dto ? dto.label : ''
    },

    // 状态转化
    getStatusText (value) {
      const dto = this.statusData.find(v => v.value === value)
      return dto ? dto.label : ''
    },

    // 项目品类的转化
    getDeviceKindText (value) {
      // 使用find方法查找特定元素对应的对象
      const selectedItem = this.deviceKindData.find(item => item.value === value)
      // 元素不存在时的处理
      return selectedItem ? selectedItem.label : ''
    },

    // 屏幕转化
    getShapeText (value) {
      const dto = this.devScrShapeData.find(v => v.value === value)
      return dto ? dto.label : ''
    },

    validateDevId () {
      const devId = this.changeStatusForm.devId
      if (!/^\d{5}$/.test(devId)) {
        this.$message.error('请检查项目ID是否输入正确，需为5位数字')
      }
    },

    // 打开日志弹窗
    handleDemandLogClick (row) {
      this.routerDialId = row.demandId
      this.demandLogDialogShow = true
    },

    handleDetail (data) {
      this.detailShow = true
      Object.keys(data).forEach(key => {
        this.form[key] = data[key]
      })
    },

    // 新增
    saveDataForm () {
      this.dialogFormVisible = true
      this.form.status = '1'
    },

    // 修改
    handleClick (data) {
      this.dialogFormVisible = true
      Object.keys(data).forEach(key => {
        this.form[key] = data[key]
      })
    },

    // 关闭dialog框
    closeDialog () {
      this.detailShow = false
      this.dialogFormVisible = false
      this.submitLoading = false
      Object.keys(this.form).forEach(key => {
        this.form[key] = ''
      })
      this.userCascadeList = []
      Object.keys(this.changeStatusForm).forEach(key => {
        this.changeStatusForm[key] = ''
      })
      this.$refs.dialogForm.resetFields()
    },

    // 关闭状态框
    closeStatusDialog () {
      this.changeStatus1Show = false
      this.submitLoading = false
      Object.keys(this.form).forEach(key => {
        this.form[key] = ''
      })
      this.userCascadeList = []
      Object.keys(this.changeStatusForm).forEach(key => {
        this.changeStatusForm[key] = ''
      })
    },

    // 关闭详情
    detailDialog () {
      this.detailShow = false
      Object.keys(this.form).forEach(key => {
        this.form[key] = ''
      })
    },

    getDemandList () {
      this.list = []
      this.$store.dispatch('getDemandList', {
        pageSize: this.pageSize,
        pageNum: this.pageNum,
        queryValue: this.queryValue,
        status: this.status,
        kind: this.kind,
        projectManager: this.projectManager
        // masterDeveloper: this.masterDeveloper
      }).then(res => {
        this.list = res.data
        this.total = res.total
      })
    },

    saveDataApi () {
      this.$refs.dialogForm.validate(valid => {
        if (!valid) return false
        this.submitLoading = true
        // const params = {
        //   demandId: '',
        //   status: '0',
        //   reserveCount: '',
        //   reserveSpace: ''
        // }
        // params.demandId = this.form.demandId
        // params.reserveCount = this.form.reserveCount
        // params.reserveSpace = this.form.reserveSpace
        this.form.status = '0'
        post('/api/crm/sys/manage/demand/saveInfo', this.form).then(req => {
          if (req && req.code === 200) {
            this.$message({ message: req.msg, type: 'success' })
          } else {
            this.$message({ message: req.msg, type: 'error' })
          }
        }).finally(() => {
          this.closeDialog()
          this.getDemandList()
          this.getDemandStatistics()
        })
      })
    },

    deleteDataApi (type) {
      if (type === 'ok') {
        post('/api/crm/sys/manage/material/configuration/deleteById', this.id
        ).then(req => {
          if (req && req.code === 200) {
            this.$message({ message: req.msg, type: 'success' })
            this.getDemandStatistics()
            this.getDemandList()
          }
        })
      }
      this.dialogVisible = false
    },

    saveStatusDataApi () {
      // 查询 devId 数据是否存在
      this.$store.dispatch('getDevManageInfo', { devId: this.changeStatusForm.devId })
        .then(req => {
          if (req && req.code === 200) {
            // 校验是否有数据
            if (req.data && Object.keys(req.data).length > 0) {
              // 如果数据存在，继续保存操作
              this.submitLoading = true
              this.changeStatusForm.status = '1' // 设置状态

              post('/api/crm/sys/manage/demand/saveInfo', this.changeStatusForm)
                .then(saveReq => {
                  if (saveReq && saveReq.code === 200) {
                    this.$message({ message: saveReq.msg, type: 'success' })
                  } else {
                    this.$message({ message: saveReq.msg, type: 'error' })
                  }
                })
                .finally(() => {
                  this.closeStatusDialog()
                  this.getDemandList()
                  this.getDemandStatistics()
                })
            } else {
              // 数据为空，提示项目未创建
              this.$message({ message: '项目未创建，请检查项目ID是否正确', type: 'error' })
            }
          } else {
            // 接口返回非 200，提示错误信息
            this.$message({ message: req.msg || '查询失败，请稍后重试', type: 'error' })
          }
        })
        .catch(err => {
          this.$message({ message: '查询失败，请稍后重试', type: 'error' })
          console.error('查询错误:', err)
        })
    },

    changeStatus0 (row) {
      this.$confirm('确认协调该项目?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        row.status = '0'
        post('/api/crm/sys/manage/demand/saveInfo', row).then(res => {
          if (res.code === 200) {
            this.$message({ message: '成功', type: 'success' })
            this.getDemandStatistics()
            this.getDemandList()
          }
        })
      })
    },

    changeStatus1 (row) {
      Object.keys(row).forEach(key => {
        this.changeStatusForm[key] = row[key]
      })
      this.changeStatus1Show = true
    },

    changeStatus3 (row) {
      this.$confirm('是否确定已完成该需求？?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        row.status = '3'
        post('/api/crm/sys/manage/demand/saveInfo', row).then(res => {
          if (res.code === 200) {
            this.$message({ message: '成功', type: 'success' })
            this.getDemandStatistics()
            this.getDemandList()
          }
        })
      })
    },

    changeStatus4 (row) {
      this.$confirm('是否确定取消该需求?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        row.status = '4'
        post('/api/crm/sys/manage/demand/saveInfo', row).then(res => {
          if (res.code === 200) {
            this.$message({ message: '成功', type: 'success' })
            this.getDemandStatistics()
            this.getDemandList()
          }
        })
      })
    },

    async getDemandStatistics () {
      // 字段名称与展示文本的映射关系
      const labelMapping = {
        total: '需求总数',
        count0: '待启动',
        count1: '进行中',
        count2: '已延期',
        count3: '已完成',
        count4: '待启动' // 如果有重复逻辑，请确认业务需求
      }
      try {
        // 调用接口获取数据
        const res = await this.$store.dispatch('getDemandStatistics', {
          projectManager: this.projectManager
          // masterDeveloper: this.masterDeveloper
        })
        const data = res.data

        // 处理数据并映射到对应的展示文本
        this.statisticsData = Object.keys(data).map((key) => ({
          label: labelMapping[key] || key, // 显示对应的文本
          value: data[key]
        }))
      } catch (error) {
        // 错误处理
        console.error('获取需求统计数据失败：', error)
        this.statisticsData = []
      }
    },

    // 根据主控平台获取对应主控型号
    getSysDictList (value) {
      this.$store.dispatch('getSysDictItemList', value).then(res => {
        this.devIcMcodeData = res
      })
    },

    // 数据字典配置分类项获取
    getDictSortData () {
      // 需求优先级
      this.$store.dispatch('getSysDictItemList', 'requirements_prioritization').then(res => {
        this.priorityData = res
      })

      // 项目品类
      this.$store.dispatch('getSysDictItemList', 'deviceKind').then(res => {
        this.deviceKindData = res
      })

      // 分辨率
      this.$store.dispatch('getSysDictItemList', 'devScrDpi').then(res => {
        const shieldDp = ['320x380', '410x502', '410x492', '172x320']
        const newArr = []
        res.forEach(item => {
          if (!shieldDp.includes(item.value)) newArr.push(item)
        })
        this.devScrDpiData = newArr
      })

      // 主控平台系列
      this.$store.dispatch('getSysDictItemList', 'devIcMseries').then(res => {
        this.devIcMseriesData = res
      })

      // 屏幕形状
      this.$store.dispatch('getSysDictItemList', 'devScrShape').then(res => {
        this.devScrShapeData = res
      })

      // flash存储空间
      this.$store.dispatch('getSysDictItemList', 'devIcFlash').then(res => {
        this.devIcFlashData = res
      })
    },

    // 用户级联关系
    getRoleCascadeRelation () {
      this.$store.dispatch('getRoleCascadeRelation').then(res => {
        const array = []
        res.forEach(item => {
          if (item.userInfoVOList && item.userInfoVOList.length) {
            array.push({
              value: item.firstLevelId,
              label: item.firstLevelName,
              children: item.userInfoVOList.map(item1 => {
                // 建立 userName 和公司名之间的映射关系
                return {
                  value: item1.userName,
                  label: item1.nickName
                }
              })
            })
          }
        })
        this.userCascadeData = array
      })
    },

    handleQuery () {
      this.pageNum = 1
      this.getDemandList()
    },

    handleSizeChange (val) {
      this.pageSize = val
      this.getDemandList()
    },

    handleCurrentChange (val) {
      this.pageNum = val
      this.getDemandList()
    },

    handleButtonClick (data) {
      this.id = data.id
      this.dialogVisible = true
    },

    handleJumpProjectManager (row) {
      // 查看项目经理
      this.handleJumpButton = true
      this.projectManager = row.projectManager
      this.handleQuery()
      this.getDemandStatistics()
    },

    handleJumpMasterDeveloper (row) {
      // 查看开发者
      this.handleJumpButton = true
      this.masterDeveloper = row.masterDeveloper
      this.handleQuery()
      this.getDemandStatistics()
    },

    // 返回上一页
    retPath () {
      this.handleJumpButton = false
      // this.masterDeveloper = ''
      this.projectManager = this.$store.state.module1.UserInfo.roleId === 4
        ? this.$store.state.module1.UserInfo.userName
        : ''
      this.handleQuery()
      this.getDemandStatistics()
    },

    is_show_button (name) {
      let show = false
      this.$store.state.module1.menu_list.forEach(v => {
        // eslint-disable-next-line eqeqeq
        if (v.path === name) {
          show = true
        }
      })
      return show
    }
  }
}
</script>

<style lang='scss'>
.page_format {
  padding: 56px 20px 140px 20px;
}

.search-form {
  margin-top: 10px;
}

.icon-image {
  width: auto;
  height: auto;
  object-fit: cover;
}
</style>
